package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 用户登录功能
 */
public class LoginDemo {
    public static void main(String[] args) {
        User user = InputUtil.getInputObject(new User(),"欢迎登录","登录");
        System.out.println(user);

        try (Connection connection = DBUtil.getConnection()) {
            /*
                SELECT id,name,password,nickname,age
                FROM userinfo
                WHERE username='XXX'
                AND password='XXX'


                拼接SQL语句存在SQL注入攻击的风险
                例如:
                恶意的用户输入用户名和密码时，密码输入类似:XXX' OR '1'='1
                此时拼接后的SQL语句变为:
                SELECT id,name,password,nickname,age
                FROM userinfo
                WHERE username='XXX'
                AND password='XXX' OR '1'='1'
                              ^^^^^^^^^^^^^^
                              输入的密码
                当拼接完毕后，密码部分改变了整个SQL的语义。
                将该SQL发送给数据库执行时，语义就发生了变化。

             */
            String sql = "SELECT id,username,password,nickname,age " +
                         "FROM userinfo " +
                         "WHERE username='"+user.getUsername()+"' " +
                         "AND password='"+user.getPassword()+"'";
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql);

            if(rs.next()){
                System.out.println("登录成功");
            }else{
                System.out.println("登录失败");
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


    }
}
